-module(hello_app).

-behaviour(application).

-export([start/2, stop/1]).

-include_lib("ehttp/include/ehttpd.hrl").


%%%===================================================================
%%% Application callbacks
%%%===================================================================

start(_StartType, _StartArgs) ->
    ehttp:start(#{ref => example_hello, port => 8888, routes => get_route(), middles => [ehttp_middle_logger, ehttp_middle_cors]}),

    hello_sup:start_link().

stop(_State) ->
    ehttp:stop(example_hello),
    ok.


%%%===================================================================
%%% Internal functions
%%%===================================================================

get_route() ->
    [
        ?EH_GET("/out", fun(_Req) -> {out, "out"} end)
        ,?EH_POST("/out_code", fun(_Req) -> {out, 500, "out_code"} end)
        ,?EH_ALL("/json", fun(_Req) -> {json, [{name, <<"mirahs">>}, {age, 18}]} end)
        ,?EH_ALL("/json2", fun(_Req) -> {json, #{name => <<"百度"/utf8>>, age => 18}} end)
        ,?EH_POST("/json_code", fun(_Req) -> {json, 500, #{name => <<"mirahs">>, age => 18}} end)

        ,?EH_GET("/redirect", fun(_Req) -> {redirect, "https://www.baidu.com/"} end)
        ,?EH_GET("/error", fun(_Req) -> {error, <<"我要进入百度了哦！"/utf8>>, "https://www.baidu.com/"} end)
        ,?EH_GET("/quick_redirect", fun(_Req) -> erlang:error({redirect, "https://www.baidu.com/"}) end)
        ,?EH_GET("/quick_error", fun(_Req) -> erlang:error({error, <<"我要进入百度了哦！"/utf8>>, "https://www.baidu.com/"}) end)

        ,?EH_GET("/sleep", fun(_Req) -> sleep(500), {out, "sleep 500(ms)"} end)

        ,?EH_GROUP("/api", [
            ?EH_GET("/test", fun(_Req) -> {out, "group api /test"} end)
            ,?EH_GET("/name/:name", fun(#{params := #{name := Name}}) -> {out, io_lib:format("group api /name name is:~s", [Name])} end)
        ])
        ,?EH_GROUP("/cp", [
            ?EH_GET("/test", fun(_Req) -> {out, "group cp /test"} end)
            ,?EH_GET("/name/:name", fun(#{params := #{name := Name}}) -> {out, io_lib:format("group cp /name name is:~s", [Name])} end)
        ])
    ].


%% 暂停(毫秒)
sleep(MilliSec) ->
    receive
    after MilliSec -> ok
    end.
